<?php
/**
 * @author spenceryg
 * @date 2023/4/20
 * @time 11:52 下午
 * @focus love & life
 */


namespace app\admin\controller\sys;


use app\admin\controller\sys\model\ConfigClass;
use app\admin\controller\sys\model\ConfigItem;
use app\BaseController;
use think\facade\View;


/**
 * 系统配置
 * Class SpConfig
 * @package app\admin\controller\sys
 */
class SpConfig extends BaseController
{
    /**
     * 配置管理
     * index
     * @return string|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        if (request()->isPost()) {
            $items = input();
            foreach ($items as $id => $value) {
                ConfigItem::update([
                    'id' => str_replace('id_', '', $id),
                    'value' => $value
                ]);
            }
            return success();
        } else {
            $classes = ConfigClass::order('sort asc, id asc')->select();
            View::assign('classes', $classes);
            $class_id = input('class_id');
            if (!$class_id) {
                $class_id = ConfigClass::order('sort asc, id asc')->value('id');
            }
            $items = ConfigItem::order('sort asc, id asc')->where('config_class_id', $class_id)->select();
            $form_items = '';
            foreach ($items as $item) {
                if (!$item['type']) {
                    $form_items .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$item['comment']}</label>
    <div class="layui-input-inline">
      <input type="text" name="id_{$item['id']}"  value="{$item['value']}"  placeholder="请输入" autocomplete="off" class="layui-input">
    </div>
</div>
EOF;

                } else {
                    $form_items .= <<<EOF
<div class="layui-form-item">
    <label class="layui-form-label">{$item['comment']}</label>
    <div class="layui-input-inline">
      <textarea type="text" name="id_{$item['id']}"    placeholder="请输入" autocomplete="off" class="layui-textarea" style="height: {$item['height']}px">{$item['value']}</textarea>
    </div>
</div>
EOF;
                }
            }
            View::assign('form_items', $form_items);
            View::assign('class_id', $class_id);
            return View::fetch(app()->getAppPath() . 'controller/sys/view/sp_config/index.html');
        }
    }
}
